package com.yeyks.app.controller.base.other;

import cn.hutool.core.util.StrUtil;
import com.yeyks.common.ajax.AjaxResponseBody;
import com.yeyks.common.constants.code.ImageCodeTypeConstant;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.utils.base.CheckUtil;
import com.yeyks.commonReference.append.other.ImageCodeService;
import com.yeyks.commonReference.append.sms.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 验证码校验接口
 */
@Api(tags = "验证码校验接口", description = "验证码校验接口")
@Controller
@RequestMapping("/app/imageCode")
public class CodeController {

    @Autowired
    private ImageCodeService imageCodeService;
    @Autowired
    private SmsService smsService;

    @ApiOperation("获取图片验证码图片v3.7.3")
    @PostMapping("/getImage")
    @ResponseBody
    public AjaxResponseBody<String> getImage(String phone) {
        CheckUtil.checkPhone(phone);
        return AjaxResponseBody.success(imageCodeService.getCode(ImageCodeTypeConstant.LOGIN, phone));
    }

    @ApiOperation("校验图片验证码并发送短信v3.7.3")
    @PostMapping("/check")
    @ResponseBody
    public AjaxResponseBody<Boolean> verify(String phone, String code) {
        CheckUtil.checkPhone(phone);
        if (StrUtil.isBlank(code)) {
            throw new ServiceException("验证码不能为空");
        }
        Boolean verify = imageCodeService.verify(ImageCodeTypeConstant.LOGIN, phone, code);
        if (verify) {
            //发送短信验证码
            try {
                smsService.sendSmsForSignup(phone);
            } catch (ServiceException e) {
                // 其它写入失败
                return AjaxResponseBody.failed(-1, e.getMessage());
            } catch (Throwable e) {
                // 其它写入失败
                return AjaxResponseBody.failed(-1, "fail");
            }
        }
        return AjaxResponseBody.success(verify);
    }

}
